define(function(require, exports, module){
	require("resource/font-awesome-4.7.0/css/font-awesome.min.css");
	require("resource/css/oaTreeStyle.css");
	var A = require("resource/js/component/ajax.js");
	var alert = require("resource/js/component/alerts.js");
	
	exports.ajaxTree = function(config){
		this.setting = { 
				view: { 
					showLine: false, 
					showIcon: false, 
					selectedMulti: false, 
					dblClickExpand: true, 
					fontCss: function getFontCss(treeId, treeNode) {
						return (treeNode.highlight) ? {color:"#A60000", "font-weight":"bold","overflow":"hidden",
							"text-overflow":"ellipsis"} : {color:"#333", "font-weight":"normal"};
					},
					addDiyDom: function(treeId, treeNode) {
						var aObj = $("#" + treeNode.tId + "_a");
						var swich = $("#" + treeNode.tId + "_switch");
						var check = $("#" + treeNode.tId + "_check").insertAfter(swich);
						if (treeNode.type == "DEPT") {
							if (treeNode.parentTId == null) {
								$('<i class="fa fa-home" aria-hidden="true"></i>').prependTo(aObj)
							} else {
								$('<i class="fa fa-map-signs" aria-hidden="true"></i>').prependTo(aObj)
							}
						} else if(treeNode.type="USER") {
							$('<i class="fa fa-user" aria-hidden="true"></i>').prependTo(aObj);
						}
					}
				}, 
		        check: {
		            enable: true,
		            chkStyle: "radio",
					radioType: "all"
		        },
		        data: {
		        	simpleData: {
		    			enable: true,
		    			idKey:"id",
		    			pidKey:"pid"
		    		}
		    	},
		    	callback:{}
		};
		
		var conf = {
			check:"checkbox",
			eid:"",
			disable:[],
			search:true,
			width:300,
			height:400,
			draggable:true,
			autoclose:true,
			title:"",
			args:{},
			save:function(){},
			checks:[],
		}
		$.extend(true,conf,config);
		this.setting.check.chkStyle = conf.check;
		config.check=undefined;
		$.extend(true,this.setting,config);
		var nodeList = [];
		var searchNode = function(key){
			var zTree = $.fn.zTree.getZTreeObj(conf.eid+"_tree");
			var value = $.trim(key);
			if(value==""){
				zTree.expandAll(false);
			}else{
				nodeList = zTree.getNodesByParamFuzzy("name", value);
				var removeHighLightNodes = zTree.getNodesByParam("highlight", true);
				$.each(removeHighLightNodes,function(i,obj){
					obj.highlight=false;
					zTree.updateNode(obj);
				});
				$.each(nodeList,function(i,obj){
					obj.highlight=true;
					zTree.updateNode(obj);
					expandNode(obj);
				});
			}
			function expandNode(e) {
				var temp  = zTree.getNodeByTId(e.parentTId);
				if(temp!=undefined){
					zTree.expandNode(temp, true, false, true, true);
				}
			}
		}
		var upfun = conf.save;
		var args = conf.args;
		var eid = conf.eid;
		if (conf.check == 'checkbox') {
			$("#" + eid).addClass('treeselect');
		} else {
			$("#" + eid).addClass('util-tree');
		}
		
		if(conf.title==""||conf.title==undefined)
			conf.title = "选择";
		if(!$('#'+conf.eid).dialog('options')||!$('#'+conf.eid).dialog('options').isLoad){
			$("#"+conf.eid).dialog(conf);
		}else if($('#'+conf.eid).dialog('options').isLoad){
			$("#"+conf.eid).panel("setTitle",conf.title);
		}
		if(!!conf.search){
			$("#"+conf.eid).dialog("initTools",[{
				type:"textbox",
				buttonText:'检索',
				buttonIcon:'icon-white-search',
				edit:true,
				iconWidth:'25',
				width:"280px",
				onClickButton: function(){
					searchNode($(this).textbox("getValue"));
				}
			}]);
		}
		$("#"+conf.eid).dialog("initButtons",[{
			text:'确定',
			iconCls:'icon-ok',
			accessKey:{akey:18,mkey:83},
			handler:function(){
				var tree = $.fn.zTree.getZTreeObj(eid+"_tree");
				var obj = tree.getCheckedNodes();
				if(obj==undefined||obj.length==0){
					obj = [{name:'',id:''}];
				}
				if(upfun)
					upfun.call($.fn.zTree.getZTreeObj(conf.eid+"_tree"),obj,args,tree);
				if(conf.autoclose){
					$('#'+eid).dialog('close');
				}
			}
		},{
			text:'关闭',
			addClass:"l-btn-red",
			accessKey:{akey:18,mkey:67},
			handler:function(){$('#'+eid).dialog('close');}
		}]);
		$("#"+conf.eid).css("overflow","auto");
		$("#"+conf.eid).panel("panel").find("input[type='textbox']").focus();
		this.close = function(){
			$('#'+conf.eid).dialog('close');
		}
		if($("#"+conf.eid+"_tree").length==0){
			$("#"+conf.eid).append("<div class='loading'></div><ul id='"+conf.eid+"_tree' class='ztree'></ul>");
		}
		
		this.open = function(){
			$('#'+conf.eid).dialog('open');
		}
		this.search = function(key){
			searchNode(key);
		};
		this.getTreeObj = function(){
			return $.fn.zTree.getZTreeObj(conf.eid+"_tree");
		};
		
		this.load = function(upfun){
			var setting = this.setting;
			var checks = "";
			if(typeof conf.checks == "string"){
				checks = conf.checks;
			}else{
				var rows = conf.checks;
				for(var key=rows.length-1;key>=0;key--){
					if(key==0){
						if(rows[key])
							checks += rows[key];
					}else{
						if(rows[key]){
							checks += rows[key]+",";
						}
					}
				}
			}
			using(["ztree","ztreecheck"],function(){
				var zNodes = [];
				$("#"+conf.eid).find(".loading").show();
				var createTree = function(data,upfun){
					$('#'+conf.eid).dialog('options').isLoad=true;
					zNodes = data;
					if(conf.disable!=undefined&&conf.disable instanceof Array){
						for(var i in conf.disable){
							for(var k in zNodes){
								if(zNodes[k].id==conf.disable[i]){
									zNodes[k].chkDisabled=true;
								}
							}
						}
					}else if(conf.disable instanceof String){
						if(conf.disable){
							for(var k in zNodes){
								if(zNodes[k].id==conf.disable){
									zNodes[k].chkDisabled=true;
								}
							}
						}
					}else if(typeof conf.disable =="function"){
						for(var k in zNodes){
							var res = conf.disable(zNodes[k]);
							if(res=="true"||!!res)
								zNodes[k].chkDisabled=true;
						}
					}
					$.fn.zTree.init($("#"+eid+"_tree"), setting, zNodes);
					if(upfun)
						upfun($.fn.zTree.getZTreeObj(eid+"_tree"),args);
					$("#"+conf.eid).find(".loading").hide();
				}
				if(conf.url){
					A.init().success(function(code,msg,data){
						if(code==0)
							createTree(data,upfun);
						else if(msg!=''){
							alert.show(msg);
							$("#"+conf.eid).find(".loading").hide();
							$("#"+conf.eid).find("ul").append("<li>"+msg+"</li>")
						}
					}).error(function(code,msg,data){
						if(msg!='')
							alert.show(msg);
						else alert.show("后台无返回数据！");

						$("#"+conf.eid).find(".loading").hide();
						$("#"+conf.eid).find("ul").append("<li>"+msg+"</li>")
					}).post(conf.url,$.extend(true,{checkeds:checks},conf.param));
				}else{
					var isInArr = function(id,ary){
						for(var k in ary){
							if(ary[k]==id) return true;
						}
						return false;
					}
					var data = [];
					if(conf.localData!=undefined&&conf.localData.length>0){
						$.each(conf.localData,function(i,item){
							if(isInArr(item.id,conf.checks))
								item.checked = true;
							data.push(item);
						});
					}
					createTree(data,upfun);
				}
			});
		}
		return this;
	}
});